package com.wecommodule.bpm.ext.biz.util;

import com.deepoove.poi.XWPFTemplate;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.Base64;
import java.util.HashMap;

/**
 * <p>
 * 封装工具类
 * </p>
 *
 * @author ZhanK
 * @since 2022-09-04
 */
@Slf4j
public class CommonUtility {





    //填充world模板
    public static void fillWord(String filePath, String targetPath) {

//        String filePath = "C:\\commonTest\\poi-tl\\table001.docx";
//        String targetPath =  "C:\\commonTest\\poi-tl\\table002.docx";

        XWPFTemplate template = XWPFTemplate.compile(filePath).render(
                new HashMap<String, Object>() {
                    {
                    }
                });
        try {
            template.writeAndClose(new FileOutputStream(targetPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    /**
     * 转换成base64编码
     * @param path
     * @return
     */
    public static String fileToBase64(String path) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(data);
        return encoder.encode(data);
    }

    /**
     * base64编码转换成文件
     * @param base64
     * @param fileName
     * @param savePath
     */
    public static void base64ToFile(String base64, String fileName, String savePath) {
        String str = "Base64转换文件完成，请在" + savePath + "目录下查看！！！";
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getMimeDecoder().decode(base64);
            fos = new FileOutputStream(savePath + "\\" + fileName);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            System.out.println("Base64转换文件完成，请在" + savePath + "目录下查看！！！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }



}
